import router from './router';

// 引入页面加载虚假进度条 START
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
// 引入页面加载虚假进度条 END
import { isHttp } from '@/utils/validate';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import usePermissionStore from '@/store/modules/permission';

NProgress.configure({ showSpinner: false });

const whiteList = ['login', 'oauth2-callback'];

let firstPageName = '';
router.beforeEach((to, from, next) => {
  NProgress.start();
  to.meta?.title && useSettingsStore().setTitle(to.meta.title);

  const isLogin = useUserStore().isLogin;
  if (whiteList.includes(to.name)) {
    // 在免登录白名单，直接进入
    next();
  } else if (!isLogin) {
    // 判断当前用户是否已拉取完user_info信息
    useUserStore()
      .getInfo()
      .then(() => {
        usePermissionStore()
          .generateRoutes()
          .then(accessRoutes => {
            firstPageName = getFirstPageName(accessRoutes);

            if (to.path !== '/') return next({ ...to, replace: true });

            if (useUserStore().roles.length) {
              if (firstPageName) next({ name: firstPageName });
              else next({ name: 'no-permiss' });
            } else {
              next({ name: 'no-role' });
            }
          });
      });
  } else if (to.path === '/') {
    if (useUserStore().roles.length) {
      if (firstPageName) next({ name: firstPageName });
      else next({ name: 'no-permiss' });
    } else {
      next({ name: 'no-role' });
    }
  } else {
    next();
  }
});

router.afterEach(() => {
  NProgress.done();
});

// 获取有权限的第一个页面
function getFirstPageName(accessRoutes) {
  accessRoutes = accessRoutes || [];
  for (let i = 0; i < accessRoutes.length; i++) {
    const ROUTE_ITEM = accessRoutes[i];
    if (ROUTE_ITEM.hidden) continue;
    if (ROUTE_ITEM?.children?.length) {
      const firsteName = getFirstPageName(ROUTE_ITEM?.children);
      if (firsteName) return firsteName;
    } else {
      return ROUTE_ITEM.name;
    }
  }
}
